package br.com.fiap.mercadinho.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import br.com.fiap.mercadinho.bean.Order;
import br.com.fiap.mercadinho.bean.Product;
import br.com.fiap.mercadinho.common.DAOException;
import br.com.fiap.mercadinho.common.GenericDAOException;

public class ProductOrderDAO extends GenericDAO {

	private static final String FIND_PRODUCTS_BY_ORDER = " SELECT A.PRODUCT_ID, A.DESCRIPTION, A.PRICE, B.QUANTITY FROM PRODUCT A, ORDER_PRODUCT B WHERE A.PRODUCT_ID = B.PRODUCT_ID AND B.ORDER_ID = ?";
	
	private static final String INSERT_PRODUCTS_ORDER = " INSERT INTO ORDER_PRODUCT (ORDER_ID,PRODUCT_ID,QUANTITY) VALUES (?,?,?)";
	
	
	public Map<Integer,Product> findProductsByOrderId(Integer orderId) throws DAOException{
		try {
			openConnection();
			PreparedStatement pst = conn.prepareStatement(FIND_PRODUCTS_BY_ORDER);
			pst.setInt(1, orderId);
			ResultSet rs = pst.executeQuery();
			
			Map<Integer, Product> listProducts = new HashMap<Integer, Product>();
			Product prod;
			
			while (rs.next()) {
				prod = buildProduct(rs);
				listProducts.put(prod.getId(), prod);
			}
			return listProducts;
		} catch (GenericDAOException | SQLException e) {
			throw new DAOException("Error in find product method: "
					+ e.getMessage());
		} finally {
			try {
				closeConnction();
			} catch (GenericDAOException e) {
				throw new DAOException("Error in close connection method: "
						+ e.getMessage());
			}
		}
	}
	
	public void saveOrderProducts(Order order) throws DAOException {
		try {
			openConnection();
			PreparedStatement pst = conn.prepareStatement(INSERT_PRODUCTS_ORDER);
			Iterator<Product> iterator = order.getProducts().values().iterator();
			Product prod;
			while (iterator.hasNext()){
				prod = iterator.next();
				pst.setInt(1, order.getId());
				pst.setInt(2, prod.getId());
				pst.setInt(3, prod.getQuantity());
				pst.executeUpdate();
			}
			
		} catch (GenericDAOException | SQLException e) {
			throw new DAOException("Error in insert product method: "
					+ e.getMessage());
		} finally {
			try {
				closeConnction();
			} catch (GenericDAOException e) {
				throw new DAOException("Error in close connection method: "
						+ e.getMessage());
			}
		}
	}
	
	private Product buildProduct(ResultSet rs) throws DAOException {
		Product product = new Product();
		try {
			product.setId(rs.getInt("PRODUCT_ID"));
			product.setDescription(rs.getString("DESCRIPTION"));
			product.setPrice(rs.getDouble("PRICE"));
			product.setQuantity(rs.getInt("QUANTITY"));
			return product;
		} catch (SQLException e) {
			throw new DAOException("Error in build product method: "
					+ e.getMessage());
		}

	}
}
